package com.trkj.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.ContractDAO;
import com.trkj.dao.DeptDAO;
import com.trkj.dao.EmpDAO;
import com.trkj.enmu.ContractType;
import com.trkj.pojo.Contract;
import com.trkj.pojo.Emp;
import com.trkj.vo.ContractEmpVo;
import com.trkj.vo.ContractInfoVo;

@Service
@Transactional
public class ContractService {
	
	/**
	 * 陈思洁
	 */
	@Autowired 
	EmpDAO empDAO;
	/**
	 * 陈思洁
	 */
	@Autowired
	DeptDAO deptDAO;
	/**
	 * 陈思洁
	 */
	@Autowired
	ContractDAO contractDAO;
	
	/**
	 * 对合同进行带条件的分页查询
	 * @author csj
	 * @param empName
	 * @param contractType
	 * @param contractState
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @return
	 */
	public Map<String, Object> pageSelectContract(String empName, String contractType, String contractState,Integer page,
			Integer rows,String sort,String order) {
		Pageable Pageable = new PageRequest(page-1, rows,new Sort(Sort.Direction.fromStringOrNull(order),sort));
		Page<Contract> resultPage = contractDAO.findAll(new Specification<Contract>() {
			@Override
			public Predicate toPredicate(Root<Contract> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				Join<Contract, Emp> join = root.join("emp", JoinType.LEFT);
				Path<ContractType> type = root.get("contractType");
				Path<String> state = root.get("contractState");
				Path<String> name = join.get("empName");
				Predicate p1 = null;
				Predicate p2 = null;
				Predicate p3 = null;
				if ((empName != null &&empName.length() > 0)
					&& (contractType != null && contractType.length() > 0)
					&& (contractState != null && contractState.length() > 0)) {
					p1 = cb.like(name, empName + "%");
					p2 = cb.equal(state, contractState);
					ContractType  Type= ContractType.valueOf(contractType);
					p3 = cb.equal(type, Type);
					return cb.and(p1,p2,p3);
					
				}else if ((empName != null &&empName.length() > 0)
						&& (contractState != null && contractState.length() > 0)) {
					p1 = cb.like(name, empName + "%");
					p2 = cb.equal(state, contractState);
					return cb.and(p1,p2);
					
				}else if ((empName != null &&empName.length() > 0)
						&& (contractType != null && contractType.length() > 0)) {
					p1 = cb.like(name, empName + "%");
					ContractType Type = ContractType.valueOf(contractType);
					p3 = cb.equal(type, Type);
					return cb.and(p1,p3);
				}else if ((contractType != null && contractType.length() > 0)
						&& (contractState != null && contractState.length() > 0)) {
					p2 = cb.equal(state, contractState);
					ContractType Type = ContractType.valueOf(contractType);
					p3 = cb.equal(type, Type);
					return cb.and(p2,p3);
				}else if ((empName != null &&empName.length() > 0)) {
					p1 = cb.like(name, empName + "%");
					return cb.and(p1);
					
				}else if ((contractState != null && contractState.length() > 0)) {
					p2 = cb.equal(state, contractState);
					return cb.and(p2);
					
				}else if ((contractType != null && contractType.length() > 0)) {
					ContractType Type = ContractType.valueOf(contractType);
					p3 = cb.equal(type, Type);
					return cb.and(p3);
				}else {
					return null;
				}
			}
		},Pageable);
		//将封装到list集合的东西再次封装到map集合中
		List<ContractInfoVo> list = contractVolist(resultPage.getContent());
		Map<String, Object> map=new HashMap<>();
		map.put("total", resultPage.getTotalElements());
		map.put("rows", list);
		return map;
		
	}
	
	/**
	 * 将vo层封装到list集合中
	 * @param list2
	 * @author csj
	 * @return
	 */
	private List<ContractInfoVo> contractVolist(List<Contract> list2) {
		// TODO Auto-generated method stub
		List<ContractInfoVo> list = new ArrayList<ContractInfoVo>();
		for(Contract contract:list2){
			list.add(contractVo(contract));
		}
		return list;
	}
	
	/**
	 * 将合同信息需要的数据封装到vo中
	 * @param emp
	 * @author csj
	 * @return
	 */
	private ContractInfoVo contractVo(Contract contract) {
		ContractInfoVo vo=new ContractInfoVo();
		vo.setContractId(contract.getContractId()+"");
		vo.setEmpName(contract.getEmp().getEmpName());
		if (contract.getEmp() !=null && contract.getEmp().getDept()!=null) {
			vo.setDeptName(contract.getEmp().getDept().getDeptName());
		}
		vo.setContractDeadtime(contract.getContractDeadtime()+"");
		Date day=new Date();
		if(contract.getContractDeadtime().getTime()<day.getTime()) {
			  contract.setContractState("过期");
		}
		vo.setContractSignedtime(contract.getContractSignedtime()+"");
		vo.setContractState(contract.getContractState());
		vo.setContractTrialtime(contract.getContractTrialtime()==null?"":contract.getContractTrialtime()+"");
		vo.setContractType(contract.getContractType()+"");
		return vo;
	}
	/**
	 * 没有合同的
	 * @author csj
	 * @return
	 */
	public List<Map<String, Object>> findUnsignedInfo(String deptName,String empName) {
		List<Emp> list = null;
		List<Map<String, Object>> list2 = new ArrayList<>();
		if(deptName!=null&&empName!=null) {
			list = empDAO.findEmpByContractsIsNullAndDeptDeptNameLikeAndEmpNameLike(deptName+"%",empName+"%");
		}else if (deptName!=null) {
			list = empDAO.findEmpByContractsIsNullAndDeptDeptNameLike(deptName+"%");
		}else if (empName!=null) {
			list = empDAO.findEmpByContractsIsNullAndEmpNameLike(empName+"%");
		}else {
			list = empDAO.findEmpByContractsIsNull();
		}
		for (Emp emp : list) {
			Map<String, Object> map = new HashMap<>();
			map.put("empName", emp.getEmpName());
			map.put("empId", emp.getEmpId());
			map.put("deptName", emp.getDept().getDeptName());
			map.put("empState", emp.getEmpState());
			list2.add(map);
		}
		return list2;
	}
	
	/**
	 * 
	 * @author csj
	 * @param empName
	 * @param deptName
	 * @return
	 */
	
	/*public List<Map<String, Object>> findUnsignedInfo1(String empName,String deptName) {
		List<Emp> list =empDAO.conditionfindcontractInfo(empName,deptName);
		List<Map<String, Object>> list2 = new ArrayList<>();
		for (Emp emp : list) {
			Map<String, Object> map = new HashMap<>();
			map.put("empName", emp.getEmpName());
			map.put("empId", emp.getEmp().getEmpId());
			map.put("deptName", emp.getDept().getDeptName());
			list2.add(map);
		}
		return list2;
	}*/
	
	
	/**
	 *查看合同表中部分员工信息
	 * @author csj
	 * @param empId
	 * @return
	 */
	public ContractEmpVo checkempInfo(Integer empId) {
		Emp emp=empDAO.findOne(empId);
		//Contract contract = contractDAO.findOne(empId);
		ContractEmpVo vo = new ContractEmpVo();
		vo.setEmpId(emp.getEmpId()+"");
		vo.setEmpName(emp.getEmpName());
		vo.setContractType("fixtimecontract");
		Date today = new Date();
		vo.setContractEffectivetime(today+"");
		vo.setContractSignedtime(today+"");
		return vo;
	}
	
	/**
	 * 保存合同信息到数据库
	 * @author csj
	 * @param contract
	 * @param empId
	 * @return
	 */
	public Integer saveUnsigned(Contract contract,Integer empId) {
		try {
			if (contract!=null) {
				if (empId!=null) {
					Emp emp = empDAO.findOne(empId);
					contract.setEmp(emp);
				}
				contract.setContractState("有效");
				contractDAO.save(contract);
				return 1;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 续签人员的合同管理
	 * @param empName
	 * @param deptName
	 * @return
	 */
	public List<Map<String, Object>> renewContractInfo(String empName,String deptName) {
		String state1="过期";
		String state2="解除";
		List<Object[]> list = null;
		String empname="";
		String deptname="";
		Map<Integer,Map<String, Object>> map2 = new HashMap<>();
		List<Map<String, Object>> list2 = new ArrayList<>();
		if (empName!=null&&deptName!=null) {
			list=contractDAO.findRenewContractANDtiaojian(state1,state2,empName+"%",deptName+"%");
		}else if (empName!=null) {
			list=contractDAO.findRenewContractORtiaojian(state1,state2,empName+"%",deptname);
		}else if (deptName!=null) {
			list=contractDAO.findRenewContractORtiaojian(state1,state2,empname,deptName+"%");
		} else {
			list=contractDAO.findRenewContract(state1,state2);
		}
		for (Object[] objects : list) {
			Map<String, Object> map = new HashMap<>();
			map.put("empId", objects[0]);
			map.put("empName", objects[1]);
			map.put("deptName", objects[2]);
			/*map.put("contractState", objects[3]);*/
			map.put("contractId", objects[4]);
			map.put("empState", objects[5]);
			map2.put(Integer.valueOf(String.valueOf(objects[0])), map);
		}
		list2.addAll(map2.values()) ;
		return list2;
	}
	
	/**
	 *查看合同表中部分员工信息
	 * @author csj
	 * @param empId
	 * @return
	 */
	public ContractEmpVo checkempAndcontactInfo(Integer contractId) {
		//Emp emp=empDAO.findOne(empId);
		Contract contract = contractDAO.findOne(contractId);
		ContractEmpVo vo = new ContractEmpVo();
		vo.setEmpId(contract.getEmp().getEmpId()+"");
		vo.setEmpName(contract.getEmp().getEmpName());
		vo.setContractId(contract.getContractId()+"");
		vo.setContractType("fixtimecontract");
		Date today = new Date();
		vo.setContractEffectivetime(today+"");
		vo.setContractSignedtime(today+"");
		return vo;
	}
	
	public ContractEmpVo checkcontactInfo(Integer contractId) {
		//Emp emp=empDAO.findOne(empId);
		Contract contract = contractDAO.findOne(contractId);
		ContractEmpVo vo = new ContractEmpVo();
		vo.setEmpId(contract.getEmp().getEmpId()+"");
		vo.setEmpName(contract.getEmp().getEmpName());
		vo.setContractId(contract.getContractId()+"");
		vo.setContractEffectivetime(contract.getContractEffectivetime()+"");
		vo.setContractSignedtime(contract.getContractSignedtime()+"");
		vo.setContractDeadtime(contract.getContractDeadtime()+"");
		vo.setContractTrialtime(contract.getContractTrialtime()+"");
		vo.setContractExplain(contract.getContractExplain());
		vo.setContractType(contract.getContractType()+"");
		return vo;
	}
	
	public boolean RelieveContract(Integer contractId) {
		try {
			Contract contract = contractDAO.findOne(contractId);
			if (contractId!=null) {
				contract.setContractState("解除");
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	

	public List<Map<String, Object>> checkContractANDyouxiao(String empName,String deptName) {
		String state="有效";
		List<Object[]> list = null;
		String empname="";
		String deptname="";
		Map<Integer,Map<String, Object>> map2 = new HashMap<>();
		List<Map<String, Object>> list2 = new ArrayList<>();
		if (empName!=null&&deptName!=null) {
			list=contractDAO.findRenewContractANDtiaojianYx(state,empName+"%",deptName+"%");
		}else if (empName!=null) {
			list=contractDAO.findRenewContractORtiaojianYx(state,empName+"%",deptname);
		}else if (deptName!=null) {
			list=contractDAO.findRenewContractORtiaojianYx(state,empname,deptName+"%");
		} else {
			list=contractDAO.findRenewContractYX(state);
		}
		for (Object[] objects : list) {
			Map<String, Object> map = new HashMap<>();
			map.put("empId", objects[0]);
			map.put("empName", objects[1]);
			map.put("deptName", objects[2]);
			/*map.put("contractState", objects[3]);*/
			map.put("contractId", objects[4]);
			map.put("empState", objects[5]);
			map2.put(Integer.valueOf(String.valueOf(objects[0])), map);
		}
		list2.addAll(map2.values()) ;
		return list2;
	}
	
	public List<Map<String, Object>> checkrenewContractlist(String empName,String deptName) {
		//查询存在有效合同的人的list集合，一个map相当于一个人
		List<Map<String, Object>> youxiao = checkContractANDyouxiao(empName, deptName);
		//查询有合同的人的list集合，一个map相当于一个人，可能存在拥有有效合同的人
		List<Map<String, Object>> notyouxiao = renewContractInfo(empName, deptName);
		List<Map<String, Object>> newmap = renewContractInfo(empName, deptName);
		for (int i = 0; i < notyouxiao.size(); i++) {
			for (int j = 0; j < youxiao.size(); j++) {
				if (notyouxiao.get(i).get("empId")==youxiao.get(j).get("empId")) {
					newmap.remove(i);
				}
			}
		}
		
		
//		for (Map<String, Object> map2 : notyouxiao) {
//			for (Map<String, Object> map3 : youxiao) {
//				if (map2.get("empId").equals(map3.get("empId"))) {
//					//如果在有合同的人中找到拥有有效合同的人，就从集合中删除
//					newmap.remove(map2);
//				}
//			}
//		}
		//最终返回有合同且不存在有效合同的人
		return newmap;
	}
	
	
}
